﻿Option Explicit On
Option Strict On

Public Class DXLogInterface

#Region " Events "

    Public Event FrequencyChanged As EventHandler(Of DXLogFrequencyChangedEventArgs)
    Public WithEvents m_DXLogCheckTimer As New System.Timers.Timer

    Private m_Radio1Frequency As Double = 0
    Private m_Radio2Frequency As Double = 0

    Public Sub Connect()
        m_DXLogCheckTimer = New System.Timers.Timer(1000)
        m_DXLogCheckTimer.AutoReset = True
        m_DXLogCheckTimer.Start()
    End Sub

    Public Sub Disconnect()
        If m_DXLogCheckTimer IsNot Nothing Then
            m_DXLogCheckTimer.Stop()
            m_DXLogCheckTimer.Dispose()
            m_DXLogCheckTimer = Nothing
        End If
    End Sub

#End Region

    Private Sub m_DXLogCheckTimer_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles m_DXLogCheckTimer.Elapsed
        Try
            Dim memoryMappedViewAccessor As System.IO.MemoryMappedFiles.MemoryMappedViewAccessor = System.IO.MemoryMappedFiles.MemoryMappedFile.OpenExisting("DXLog.net.mmf").CreateViewAccessor()


            Dim NewRadio1Frequency As Double = memoryMappedViewAccessor.ReadDouble(0)
            Dim NewRadio2Frequency As Double = memoryMappedViewAccessor.ReadDouble(30)

            If m_Radio1Frequency <> NewRadio1Frequency Then
                RaiseEvent FrequencyChanged(Me, New DXLogFrequencyChangedEventArgs(CInt(m_Radio1Frequency), 1))
                m_Radio1Frequency = NewRadio1Frequency
            End If

            If m_Radio2Frequency <> NewRadio2Frequency Then
                RaiseEvent FrequencyChanged(Me, New DXLogFrequencyChangedEventArgs(CInt(m_Radio2Frequency), 2))
                m_Radio2Frequency = NewRadio2Frequency
            End If


            'If we we're succesfull and we are running on the slower timer, increase the polling speed
            If m_DXLogCheckTimer.Interval = 5000 Then
                m_DXLogCheckTimer.Interval = 1000
            End If

        Catch ex As System.IO.FileNotFoundException
            'DX Logger isn't running, so reduce the timer interval to 5 seconds
            m_DXLogCheckTimer.Interval = 5000

            'Reset the frequencies to Zero
            m_Radio1Frequency = 0
            m_Radio2Frequency = 0

        End Try
        
    End Sub

End Class
